﻿using Manon.Admin.ApplicationCore.Common;
using Manon.Admin.ApplicationCore.Infrastructure;
using Manon.Admin.Web.ApplicationCore.Dtos.Settings;
using Manon.Admin.Web.ApplicationCore.Entities.Settings;
using Manon.Admin.Web.ApplicationCore.Entities.Sys;
using Manon.Admin.Web.ApplicationCore.Interfaces;
using Manon.Core.IOC;
using Manon.Core.Commons;
using Manon.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Manon.Admin.Web.ApplicationCore.Services
{
    public class SettingsService : ISettingsService
    {
        /// <summary>
        /// 获取用户基本设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetBaseSettingsOutput> GetBaseSettings()
        {

            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<BaseSettings>().GetFirstOrDefaultAsync();
                if (result == null) return new GetBaseSettingsOutput();
                return result.ConvertTo<BaseSettings, GetBaseSettingsOutput>();
         
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户基本设置异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存基本设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveBaseSettings(SaveBaseSettingsInput Input)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<BaseSettings>();


                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new BaseSettings();
                    result.CopyRight = Input.CopyRight;
                    result.Description = Input.Description;
                    result.IsDeleted = false;
                    result.Keyword = Input.Keyword;
                    result.RecordCode = Input.RecordCode;
                    result.StatisticalCode = Input.StatisticalCode;
                    result.WebsiteName = Input.WebsiteName;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.CopyRight = Input.CopyRight;
                    result.Description = Input.Description;
                    result.IsDeleted = false;
                    result.Keyword = Input.Keyword;
                    result.RecordCode = Input.RecordCode;
                    result.StatisticalCode = Input.StatisticalCode;
                    result.WebsiteName = Input.WebsiteName;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"保存基本设置异常，入参input={JsonConvert.SerializeObject(Input)}", ex);
                throw;
            }
        }



        /// <summary>
        /// 获取用户基本的安全设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetBaseSafeSettingsOutput> GetSafesettings()
        {

            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<BaseSafeSettings>().GetFirstOrDefaultAsync();
                if (result == null) return new GetBaseSafeSettingsOutput();
                return result.ConvertTo<BaseSafeSettings, GetBaseSafeSettingsOutput>(); 
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户基本的安全设置异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存基本安全设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveBaseSafeSettings(SaveBaseSafeSettingsInput Input)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<BaseSafeSettings>();


                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new BaseSafeSettings();
                    result.AllowIp = Input.AllowIp;
                    result.IsDeleted = false;
                    result.FailedLoginTimes = Input.FailedLoginTimes;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.IsDeleted = false;
                    result.AllowIp = Input.AllowIp;
                    result.FailedLoginTimes = Input.FailedLoginTimes;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"保存基本安全设置异常，入参input={JsonConvert.SerializeObject(Input)}", ex);
                throw;
            }
        }




        /// <summary>
        /// 获取用户基本的安全设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetBaseEmailSettingsOutput> GetEmailSettings()
        {

            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<BaseEmailSettings>().GetFirstOrDefaultAsync();
                if (result == null) return new GetBaseEmailSettingsOutput();
                return result.ConvertTo<BaseEmailSettings, GetBaseEmailSettingsOutput>();
        
            }
            catch (Exception ex)
            {
                logger.LogError("获取用户基本的安全设置异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存基本邮件设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveBaseEmailSettings(SaveBaseEmailSettingsInput Input)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<BaseEmailSettings>();


                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new BaseEmailSettings();
                    result.Email = Input.Email;
                    result.EmailPassword = Input.EmailPassword;
                    result.ReceiveEmail = Input.ReceiveEmail;
                    result.SendMode = Input.SendMode;
                    result.SMTP_IP = Input.SMTP_IP;
                    result.SMTP_Port = Input.SMTP_Port;

                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.IsDeleted = false;
                    result.Email = Input.Email;
                    result.EmailPassword = Input.EmailPassword;
                    result.ReceiveEmail = Input.ReceiveEmail;
                    result.SendMode = Input.SendMode;
                    result.SMTP_IP = Input.SMTP_IP;
                    result.SMTP_Port = Input.SMTP_Port;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"保存基本邮件设置异常，入参input={JsonConvert.SerializeObject(Input)}", ex);
                throw;
            }
        }




        /// <summary>
        /// 获取屏蔽词
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetGetSysShieldingOutput> GetSysShielding()
        {

            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<SysShielding>().GetFirstOrDefaultAsync();
                if (result == null) return new GetGetSysShieldingOutput();
                return result.ConvertTo<SysShielding, GetGetSysShieldingOutput>(); 
            }
            catch (Exception ex)
            {
                logger.LogError("获取屏蔽词异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存屏蔽词
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveSysShielding(SaveSysShieldingInput Input)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<SysShielding>();


                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new SysShielding();
                    result.ShieldingWord = Input.ShieldingWord;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.IsDeleted = false;
                    result.ShieldingWord = Input.ShieldingWord;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"保存屏蔽词异常，入参input={JsonConvert.SerializeObject(Input)}", ex);
                throw;
            }
        }



        #region 栏目
        /// <summary>
        /// 获取栏目
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetChanelListTreeOutput>> GetChanelListTree()
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<Chanel>().GetAllByWhere(n => n.IsDeleted == false).ToListAsync();
                if (result == null) return new List<GetChanelListTreeOutput>();

                List<GetChanelListTreeOutput> list = GetChanelListTreeChild(result, 0);
                return list;
            }
            catch (Exception ex)
            {
                logger.LogError("获取栏目异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取栏目子集
        /// </summary>
        /// <param name="result"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private List<GetChanelListTreeOutput> GetChanelListTreeChild(List<Chanel> result, int ParentId)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var top = result.Where(n => n.ParentId == ParentId).OrderBy(n => n.OrderIndex).ToList();
                if (top == null) return null;

                List<GetChanelListTreeOutput> list = new List<GetChanelListTreeOutput>();
                foreach (var item in top)
                {
                    GetChanelListTreeOutput model = JsonConvert.DeserializeObject<GetChanelListTreeOutput>(JsonConvert.SerializeObject(item));
                    var itemResult = result?.Where(n => n.ParentId == item.Id).ToList();


                    model.Children = JsonConvert.DeserializeObject<List<GetChanelListTreeOutput>>(JsonConvert.SerializeObject(itemResult));
                    if (model.Children != null && model.Children.Count != 0)
                    {
                        foreach (var child in model.Children)
                        {
                            child.Children = GetChanelListTreeChild(result, child.Id);
                        }
                    }
                    list.Add(model);
                }
                return list;
            }
            catch (Exception ex)
            {
                logger.LogError("获取栏目子集异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 保存栏目
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveChanel(SaveChanelInput Input)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<Chanel>();


                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new Chanel();
                    result.Alisa = Input.Alisa;
                    result.Code = Input.Code;
                    result.Description = Input.Description;
                    result.IsDeleted = false;
                    result.Keyword = Input.Keyword;
                    result.Name = Input.Name;
                    result.Enabled = Input.Enabled;
                    result.OrderIndex = Input.OrderIndex;
                    result.ParentId = Input.ParentId;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.Alisa = Input.Alisa;
                    result.Code = Input.Code;
                    result.Description = Input.Description;
                    result.IsDeleted = false;
                    result.Keyword = Input.Keyword;
                    result.Name = Input.Name;
                    result.Enabled = Input.Enabled;
                    result.OrderIndex = Input.OrderIndex;
                    result.ParentId = Input.ParentId;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"保存栏目异常，入参input={JsonConvert.SerializeObject(Input)}", ex);
                throw;
            }
        }


        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> DeleteChanel(int Id)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<Chanel>();


                var result = await repos.FindAsync(Id);
                if (result == null)
                {
                    return Result.Failed("栏目不存在");
                }
                result.IsDeleted = true;
                repos.Update(result);
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("删除栏目成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"删除栏目异常，入参Id={Id}", ex);
                throw;
            }
        }

        /// <summary>
        /// 设置栏目启用/禁用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetChanelEnabled(int Id, bool Enabled)
        {
            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<Chanel>();


                var result = await repos.FindAsync(Id);
                if (result == null)
                {
                    return Result.Failed("栏目不存在");
                }
                result.Enabled = Enabled;
                repos.Update(result);
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置栏目成功!");
            }
            catch (Exception ex)
            {
                logger.LogError($"设置栏目启用/禁用异常，入参Id={Id};Enabled={Enabled}", ex);
                throw;
            }
        }


        /// <summary>
        /// 获取栏目
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetChanelListTreeOutput> GetChanel(int Id)
        {

            var logger = Resolver.GetService<ILogger<UserService>>();
            try
            {
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<Chanel>().FindAsync(Id);
                return result.ConvertTo<Chanel, GetChanelListTreeOutput>(); 
            }
            catch (Exception ex)
            {
                logger.LogError("获取栏目异常", ex);
                throw;
            }
        }
        #endregion
    }
}
